package com.yyf.blogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yyf.blogapi.po.SysUser;
import com.yyf.blogapi.mapper.SysUserMapper;
import com.yyf.blogapi.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyf.blogapi.util.JwtUtil;
import com.yyf.blogapi.vo.LoginParam;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yyf
 * @since 2021-08-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Value("${md5.salt}")
    private String salt;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public SysUser getUserByAccountAndPassword(String account, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, account)
                .eq(SysUser::getPassword, password)
                .select(SysUser::getId, SysUser::getAccount, SysUser::getAvatar, SysUser::getNickname)
                .last("limit 1");
        return sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public String register(LoginParam loginParam) {
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickname = loginParam.getNickname();
        SysUser sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password + salt));
        sysUser.setCreateDate(new Timestamp(System.currentTimeMillis()));
        sysUser.setLastLogin(new Timestamp(System.currentTimeMillis()));
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(true); //1 为true
        sysUser.setDeleted(false); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserMapper.insert(sysUser);
        String token = jwtUtil.generateToken(sysUser.getId());
        redisTemplate.opsForValue().set("userId_" + sysUser.getId(), token, 1, TimeUnit.DAYS);
        return token;
    }

    @Override
    public SysUser getUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        return sysUserMapper.selectOne(queryWrapper.eq(SysUser::getAccount, account).last("limit 1"));
    }

    @Override
    public SysUser checkToken(String token) {
        Claims claims = jwtUtil.getClaims(token);
        if (claims == null) {
            return null;
        }
        Long userId = Long.valueOf(String.valueOf(claims.get("userId")));
        String redisToken = (String) redisTemplate.opsForValue().get("userId_" + userId);
        if (StringUtils.isBlank(redisToken)) {
            return null;
        }

        return sysUserMapper.selectById(userId);
    }

    @Override
    public void updateLastLogin(SysUser user) {
        user.setLastLogin(new Timestamp(System.currentTimeMillis()));
        sysUserMapper.updateById(user);
    }
}
